import { LockOutlined, MobileOutlined, UserOutlined } from '@ant-design/icons';
import { Alert, message, Modal, Tabs } from 'antd';
import React, { useState } from 'react';
import { ProFormCaptcha, ProFormCheckbox, ProFormText, LoginForm } from '@ant-design/pro-form';
import Marquee from 'react-fast-marquee';
import { useIntl, history, FormattedMessage, SelectLang, useModel } from 'umi';
import Footer from '@/components/Footer';

import {
  usernameAndPasswordLogin,
  getSmsCode,
  getQQLoginUrl,
  getWeChatLoginUrl, mobileLogin,
} from '@/services/onepiece/onepiece-server';

import styles from './index.less';

const LoginMessage = ({ content }) => (
  <Alert
    style={{
      marginBottom: 24,
    }}
    message={content}
    type="error"
    showIcon
  />
);

// const qrcodeTicket = await getQrcodeTicket({});
const qqLoginUrl = await getQQLoginUrl({});
const weChatLoginUrl = await getWeChatLoginUrl({});

const Login = () => {
  const [userLoginState, setUserLoginState] = useState({});
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [type, setType] = useState('account');
  const { initialState, setInitialState } = useModel('@@initialState');
  const intl = useIntl();

  const showModal = () => {
    setIsModalVisible(true);
  };

  const handleOk = () => {
    setIsModalVisible(false);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const fetchUserInfo = async () => {
    const userInfo = await initialState?.fetchUserInfo?.();
    if (userInfo) {
      await setInitialState((s) => ({ ...s, currentUser: userInfo }));
    }
  };

  const handleSubmit = async (values) => {
    try {
      console.log('登录类型：' + type);
      console.log(values);
      // 登录
      let result = null;
      if (type === 'account'){
        result = await usernameAndPasswordLogin({ ...values});
      }else if (type === 'mobile'){
        result = await mobileLogin({ ...values});
      }

      if (result.success) {
        const defaultLoginSuccessMessage = intl.formatMessage({
          id: 'pages.login.success',
          defaultMessage: '登录成功！',
        });

        // 登录成功，则将token存储到本地缓存
        console.log(result.data)
        console.log(result)
        localStorage.setItem("token", result.data);
        message.success(defaultLoginSuccessMessage);

        // 获取用户信息
        await fetchUserInfo();
        /** 此方法会跳转到 redirect 参数所在的位置 */
        if (!history) return;
        const { query } = history.location;
        const { redirect } = query;
        console.log(redirect)
        if (redirect){
          history.push(redirect || '/');
        }else {
          window.location.href = '/admin/home'
        }
        return;
      }else {
        console.log(result.msg);
        message.error(result.msg);
      }

      const jsonResult = {
        "currentAuthority" : "admin",
        "status" : "ok",
        "type" : type
      }
      setUserLoginState(jsonResult);

    } catch (error) {
      console.log(error)
    }
  };

  const { status, type: loginType } = userLoginState;
  return (
    <div className={styles.container}>
      <Alert
        banner
        message={
          <Marquee pauseOnHover gradient={false}>
            优先推荐大家使用QQ/微信扫码授权登录（也可以使用微信公众号授权），QQ/微信登录自动授权注册之后，可以在个人设置页绑定自己的手机号和账号密码，之后方可通过账号密码或者手机短信认证的方式进行登录！
          </Marquee>
        }
      />
      <div className={styles.lang} data-lang>
        {SelectLang && <SelectLang />}
      </div>
      <div className={styles.content}>
        <LoginForm
          logo={<img alt="logo" src="/logo.svg" />}
          title="OnePiece社区后台"
          subTitle={intl.formatMessage({
            id: 'pages.layouts.userLayout.title',
          })}
          initialValues={{
            autoLogin: true,
          }}
          actions={[
            <FormattedMessage
              key="loginWith"
              id="pages.login.loginWith"
              defaultMessage="其他登录方式"
            />,
            // <a key={"mq-wechat"} style={{marginLeft:5,marginRight:5}}>
            //   <img src={"http://csp-aliyun-oos01.oss-cn-beijing.aliyuncs.com/onepiece/2022/06/08/722b1741-fdec-409a-9027-209582ba3490.png"} onClick={showModal} />
            // </a>,
            <a key={'open-wechat'} style={{ marginLeft: 5, marginRight: 5 }} href={weChatLoginUrl}>
              <img
                src={
                  'https://open.weixin.qq.com/zh_CN/htmledition/res/assets/res-design-download/icon24_appwx_logo.png'
                }
              />
            </a>,
            <a href={qqLoginUrl} key={'qq'}>
              <img
                src={'https://wiki.connect.qq.com/wp-content/uploads/2021/01/bt_white_24X24.png'}
              />
            </a>,
          ]}
          onFinish={async (values) => {
            await handleSubmit(values);
          }}
        >
          <Tabs activeKey={type} onChange={setType}>
            <Tabs.TabPane
              key="account"
              tab={intl.formatMessage({
                id: 'pages.login.accountLogin.tab',
                defaultMessage: '账户密码登录',
              })}
            />
            <Tabs.TabPane
              key="mobile"
              tab={intl.formatMessage({
                id: 'pages.login.phoneLogin.tab',
                defaultMessage: '手机号登录',
              })}
            />
          </Tabs>

          {status === 'error' && loginType === 'account' && (
            <LoginMessage
              content={intl.formatMessage({
                id: 'pages.login.accountLogin.errorMessage',
                defaultMessage: '账户或密码错误(admin/ant.design)',
              })}
            />
          )}
          {type === 'account' && (
            <>
              <ProFormText
                name="username"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined className={styles.prefixIcon} />,
                }}
                placeholder={intl.formatMessage({
                  id: 'pages.login.username.placeholder',
                  defaultMessage: '用户名: admin or user',
                })}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.username.required"
                        defaultMessage="请输入用户名!"
                      />
                    ),
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={styles.prefixIcon} />,
                }}
                placeholder={intl.formatMessage({
                  id: 'pages.login.password.placeholder',
                  defaultMessage: '密码: ant.design',
                })}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.password.required"
                        defaultMessage="请输入密码！"
                      />
                    ),
                  },
                ]}
              />
            </>
          )}

          {status === 'error' && loginType === 'mobile' && <LoginMessage content="验证码错误" />}
          {type === 'mobile' && (
            <>
              <ProFormText
                fieldProps={{
                  size: 'large',
                  prefix: <MobileOutlined className={styles.prefixIcon} />,
                }}
                name="phone"
                placeholder={intl.formatMessage({
                  id: 'pages.login.phoneNumber.placeholder',
                  defaultMessage: '手机号',
                })}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.phoneNumber.required"
                        defaultMessage="请输入手机号！"
                      />
                    ),
                  },
                  {
                    pattern: /^1\d{10}$/,
                    message: (
                      <FormattedMessage
                        id="pages.login.phoneNumber.invalid"
                        defaultMessage="手机号格式错误！"
                      />
                    ),
                  },
                ]}
              />
              <ProFormCaptcha
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined className={styles.prefixIcon} />,
                }}
                captchaProps={{
                  size: 'large',
                }}
                placeholder={intl.formatMessage({
                  id: 'pages.login.captcha.placeholder',
                  defaultMessage: '请输入验证码',
                })}
                captchaTextRender={(timing, count) => {
                  if (timing) {
                    return `${count} ${intl.formatMessage({
                      id: 'pages.getCaptchaSecondText',
                      defaultMessage: '获取验证码',
                    })}`;
                  }
                  return intl.formatMessage({
                    id: 'pages.login.phoneLogin.getVerificationCode',
                    defaultMessage: '获取验证码',
                  });
                }}
                // 手机号的 name，onGetCaptcha 会注入这个值
                phoneName="phone"
                name="captcha"
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.captcha.required"
                        defaultMessage="请输入验证码！"
                      />
                    ),
                  },
                ]}
                onGetCaptcha={async (phone) => {
                  // 获取短信验证码
                  const result = await getSmsCode({
                    phone,
                  });
                  if (result.success) {
                    message.success(result.msg);
                  } else {
                    message.error(result.msg);
                  }
                }}
              />
            </>
          )}
          <div
            style={{
              marginBottom: 24,
            }}
          >
            <ProFormCheckbox noStyle name="autoLogin">
              <FormattedMessage id="pages.login.rememberMe" defaultMessage="自动登录" />
            </ProFormCheckbox>
            <a
              style={{
                float: 'right',
              }}
            >
              <FormattedMessage id="pages.login.forgotPassword" defaultMessage="忘记密码" />
            </a>
          </div>
        </LoginForm>
        <Modal
          title="请使用微信扫码，并关注公众号登录"
          visible={isModalVisible}
          onOk={handleOk}
          onCancel={handleCancel}
          footer={null}
          style={{ textAlign: 'center' }}
        >
          {/*<img src={"https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + qrcodeTicket.ticket}/>*/}
        </Modal>
      </div>
      <Footer />
    </div>
  );
};

export default Login;
